package com.gz.mylife.app.llopendoor;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.google.zxing.WriterException;
import com.gz.mylife.R;
import com.gz.mylife.util.CodeCreator;
import com.gz.mylife.util.NetworkUtil;
import com.gz.mylife.util.PrefUtils;
import com.izhihuicheng.api.lling.LLingOpenDoorConfig;
import com.izhihuicheng.api.lling.LLingOpenDoorHandler;
import com.izhihuicheng.api.lling.LLingOpenDoorStateListener;
import com.zl.smartmall.library.po.KeysBean;
import com.zl.smartmall.library.util.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FagmentOpenDoor extends Fragment implements OnClickListener{
	private View mConvertView;
	private static final String TAG = FagmentOpenDoor.class.getSimpleName();
	private LinearLayout ly_top;
	private ImageView img_erweima;
	private TextView tx_btnopen;
	private ImageView img_message;
	private TextView tx_message;
	private TextView tx_open;
	private TextView tx_btnactivity;
	private TextView tx_visitor;

	public static final int RS_OD_SUCCESS = 1;
	public static final int RS_OD_FAILD = 2;
	public static final int RS_OD_ERROR = 3;
	public static final int RS_CONN_ERROR = 4;
	public static final int RS_CONN_NOFOUND = 5;
	private RefreshReceiver mRefreshReceiver;
	private List<String> keys = new ArrayList<String>();
	private List<KeysBean> keydoor = new ArrayList<KeysBean>(); 
	private Date date=new Date();
	private DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
	private SensorManager sensorManager;
    private Vibrator vibrator;
    private static final int UPTATE_INTERVAL_TIME = 50;
    private static final int SPEED_SHRESHOLD = 20;//这个值调节灵敏度
    private long lastUpdateTime;
    private float lastX;
    private float lastY;
    private float lastZ;
    public static int activityActive = 0; //全局变量,表示当前在前台的activity数量
    public static boolean isBackground ;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (mConvertView == null) {
			mConvertView = inflater.inflate(R.layout.activity_maindoor, container,
					false);
			initview();
		}

		return mConvertView;
	}

	private void initview(){
		ly_top = (LinearLayout)mConvertView.findViewById(R.id.ly_top);
		img_erweima = (ImageView) mConvertView.findViewById(R.id.img_erweima);
		tx_btnopen = (TextView) mConvertView.findViewById(R.id.tx_btnopen);
		tx_btnopen.setOnClickListener(this);
		tx_open = (TextView) mConvertView.findViewById(R.id.tx_open);
		tx_open.setOnClickListener(this);
		tx_btnactivity = (TextView) mConvertView.findViewById(R.id.tx_btnactivity);
		tx_btnactivity.setOnClickListener(this);
		tx_visitor = (TextView) mConvertView.findViewById(R.id.tx_visitor);
		tx_visitor.setOnClickListener(this);
		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int widthPixels = metrics.widthPixels;
		ViewGroup.LayoutParams params = ly_top.getLayoutParams();
		params.height = widthPixels + 40;
		params.width = widthPixels - 20;
		ly_top.setLayoutParams(params);
		ViewGroup.LayoutParams params1 = img_erweima.getLayoutParams();
		params1.height = widthPixels - 40;
		params1.width = widthPixels - 40;
		img_erweima.setLayoutParams(params1);
		img_message = (ImageView) mConvertView.findViewById(R.id.img_message);
		tx_message = (TextView) mConvertView.findViewById(R.id.tx_message);   
		sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);// 传感器
		vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);// 震动器

		
		mRefreshReceiver = new RefreshReceiver();
		IntentFilter intentFilter = new IntentFilter("updateUI");
		getActivity().registerReceiver(mRefreshReceiver,intentFilter);
	}
	private class RefreshReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			getkeys();
		}
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (arg0.getId()) {
		case R.id.tx_btnopen:
			String[] key = (String[])keys.toArray(new String[0]);
			LLingOpenDoorConfig config = new LLingOpenDoorConfig(9, key);   
			LLingOpenDoorHandler handler = LLingOpenDoorHandler.getSingle(getActivity());
			handler.doOpenDoor(config, listener);
			break;
		case R.id.tx_open://跳转到激活功能
			/*intent = new Intent(getActivity(),OpenActivationActivity.class);
			startActivity(intent);*/
			Toast.makeText(getActivity(), "此功能暂未开放", Toast.LENGTH_LONG).show();
			break;
		case R.id.tx_btnactivity:
			/*intent = new Intent(getActivity(),OpenActivationActivity.class);
			startActivity(intent);*/
			Toast.makeText(getActivity(), "此功能暂未开放", Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
	}



	@Override  
	public void setUserVisibleHint(boolean isVisibleToUser) {  
		super.setUserVisibleHint(isVisibleToUser);  
		if (isVisibleToUser) {  
			if (sensorManager != null) {// 注册摇一摇监听器
				sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
				// 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
			}
			//相当于Fragment的onResume 
			if ("".equals(PrefUtils.getStrPrefData(getActivity(), "linglingID", ""))) {//查看用户是否已经激活过
				tx_btnactivity.setVisibility(View.VISIBLE);
				tx_btnopen.setVisibility(View.GONE);
				img_message.setBackgroundResource(R.drawable.cat2);
				tx_message.setText("如您小区安装有手机开门设备，请联系物业索取激活码!");
			}else{
				if (keys.size()>0) {
					tx_btnactivity.setVisibility(View.GONE);
					tx_btnopen.setVisibility(View.VISIBLE);
					try {
						String qrStr = LLingOpenDoorHandler
								.getSingle(getActivity()).createDoorControlQR(PrefUtils.getStrPrefData(getActivity(), "linglingID", ""), keys, 10, 3, 0, "123456AA");//llingId, keys, validTime, validCount, authLevel(梯控参数，门禁则默认0), encryptKey
						Bitmap bitmap = CodeCreator.createQRCode(qrStr);
						img_erweima.setImageBitmap(bitmap);
					} catch (WriterException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}else{
					tx_btnactivity.setVisibility(View.GONE);
					tx_btnopen.setVisibility(View.VISIBLE);
					img_message.setBackgroundResource(R.drawable.cat4);
					tx_message.setText("您的开门权限已过期，请联系物业！");
					img_erweima.setBackgroundResource(R.drawable.defaulterweima);
				}
			} 
		}else {
			//相当于Fragment的onPause 
			if (sensorManager != null) {
	            sensorManager.unregisterListener(sensorEventListener);
	        }
		}  

	} 

	@Override
	public void onPause() {
		super.onPause();
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if ("".equals(PrefUtils.getStrPrefData(getActivity(), "linglingID", ""))) {//查看用户是否已经激活过
			tx_btnactivity.setVisibility(View.VISIBLE);
			tx_btnopen.setVisibility(View.GONE);
			img_message.setBackgroundResource(R.drawable.cat2);
			tx_message.setText("如您小区安装有手机开门设备，请联系物业索取激活码!");
		}else{
			tx_btnactivity.setVisibility(View.GONE);
			tx_btnopen.setVisibility(View.VISIBLE);
			if (PrefUtils.getStrPrefData(getActivity(), "keys","").length()==0) {
				getkeys();
			}else{
				JSONArray jsonArray;
				try {
					jsonArray = new JSONArray(PrefUtils.getStrPrefData(getActivity(), "keys", ""));
					keydoor.clear();
					keydoor.addAll(KeysBean.parse(jsonArray));
					for (int i = 0; i < keydoor.size(); i++) {
						try {
							if (format.parse(format.format(date)).getTime()-format.parse(keydoor.get(i).getEnd_date()).getTime()<0) {
								keys.add(keydoor.get(i).getKey());
							}else{
								keydoor.remove(i);
							}
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				getkeys();

			}
		}
	}

	private LLingOpenDoorStateListener listener = new LLingOpenDoorStateListener() {

		public void onOpenSuccess(String deviceKey, String sn, int openType) {
			Log.i("BORTURN", "开门结束：" + System.currentTimeMillis());

		};

		public void onOpenFaild(int errCode, int openType, String deviceKey,
				String sn, String desc) {
			switch (errCode) {
			case RS_CONN_ERROR:

				vibrator.cancel();
				Log.i("BORTURN", "设备连接失败!");
				break;
			case RS_CONN_NOFOUND:

				vibrator.cancel();
				Log.i("BORTURN", "设备未找到!");
				break;
			case RS_OD_ERROR:
				Log.i("BORTURN", "开门异常!");
				vibrator.cancel();
				break;
			case RS_OD_FAILD:
				Log.i("BORTURN", "开门失败!");
				vibrator.cancel();
				break;
			default:
				break;
			}
		};

		public void onConnectting(String deviceKey, String sn, int openType) {
			Log.i("BORTURN", "开始连接!");
		};

		public void onFoundDevice(String deviceKey, String sn, int openType) {
			Log.i("BORTURN", "找到可用的设备!");
		};

		public void onRunning() {
			Log.i("BORTURN", "onRunning");
		};

	};

	/**
	 * 登录
	 */
	/*private void login() {
		if (NetworkUtil.isNetworkConnected(getActivity())) {
			String url = Constants.OPENLOGIN;
			RequestParams params = new RequestParams(url);
			params.addParameter("phone", "");//手机号
			params.addParameter("phone_sn", PhoneSN.getPhoneSN(getActivity()));//手机唯一标识
			params.addParameter("code", "");
			Log.i("duzhijuan", params + "");
			x.http().get(params, new Callback.CommonCallback<String>() {

				@Override
				public void onCancelled(CancelledException arg0) {
					// TODO Auto-generated method stub
					Log.e("cancelled", arg0.toString());
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// TODO Auto-generated method stub
					Log.e("onError", arg0.toString());
				}

				@Override
				public void onFinished() {
					// TODO Auto-generated method stub
					Log.e("onFinished","onFinished");
				}

				@Override
				public void onSuccess(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject jsonObject = new JSONObject(result);
						if ("0".equals(jsonObject.getString("ref"))) {//登录成功说明此手机之前已经使用过令令开门功能
							PrefUtils.setStrPrefData(getActivity(), "linglingID", jsonObject.getString("result"));
							img_message.setBackgroundResource(R.drawable.cat4);
							tx_message.setText("告诉你一个秘密手机摇一摇也可以开门哦！本二维码可在10分钟使用3次，您再次进入系统会重新生成！");
							tx_btnactivity.setVisibility(View.GONE);
							tx_btnopen.setVisibility(View.VISIBLE);
							getkeys();//获取秘钥keys
						}else{
							//登录失败说明用户未激活过或者是更换了设备
							Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
							img_message.setBackgroundResource(R.drawable.cat2);
							img_erweima.setBackgroundResource(R.drawable.defaulterweima);
							tx_btnactivity.setVisibility(View.VISIBLE);
							tx_btnopen.setVisibility(View.GONE);
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}


			});
		}else{
			Toast.makeText(getActivity(), "糟糕,网络异常!", Toast.LENGTH_LONG).show();
		}

	}*/
	/**
	 * 获取秘钥
	 */
	private void getkeys() {

		if (NetworkUtil.isNetworkConnected(getActivity())) {
			String url = Constants.GET_KEYS;
			RequestParams params = new RequestParams(url);
			params.addParameter("phone", PrefUtils.getStrPrefData(getActivity(), "user_phone", ""));//手机号
			Log.i("duzhijuan", params + "");
			x.http().get(params, new Callback.CommonCallback<String>() {

				@Override
				public void onCancelled(CancelledException arg0) {
					// TODO Auto-generated method stub
					Log.e("cancelled", arg0.toString());
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// TODO Auto-generated method stub
					Log.e("onError", arg0.toString());
				}

				@Override
				public void onFinished() {
					// TODO Auto-generated method stub
					Log.e("onFinished","onFinished");
				}

				@Override
				public void onSuccess(String result) {
					// TODO Auto-generated method stub
					try {
						JSONObject jsonObject = new JSONObject(result);
						if ("0".equals(jsonObject.getString("ref"))) {//登录成功说明此手机之前已经使用过令令开门功能
							if (jsonObject.getJSONArray("result").toString().length()==0) {
								tx_btnactivity.setVisibility(View.VISIBLE);
								tx_btnopen.setVisibility(View.GONE);
								img_message.setBackgroundResource(R.drawable.cat4);
								tx_message.setText("您的开门权限未开通,请联系物业！");
								img_erweima.setBackgroundResource(R.drawable.defaulterweima);
							}else{
								PrefUtils.setStrPrefData(getActivity(), "keys", jsonObject.getJSONArray("result").toString());//保存秘钥到本地
								keys.clear();
								for (int i = 0; i < jsonObject.getJSONArray("result").length(); i++) {
									JSONObject jsonObject2 = new JSONObject(jsonObject.getJSONArray("result").get(i).toString());
									if (format.parse(format.format(date)).getTime()-format.parse(jsonObject2.getString("end_date")).getTime()<0) {
										keys.add(jsonObject2.getString("key"));
									}

								}

								if (keys.size()==0) {
									tx_btnactivity.setVisibility(View.GONE);
									tx_btnopen.setVisibility(View.VISIBLE);
									img_message.setBackgroundResource(R.drawable.cat4);
									tx_message.setText("您的开门权限已过期，请联系物业！");
									img_erweima.setBackgroundResource(R.drawable.defaulterweima);
								}else{
									tx_btnactivity.setVisibility(View.GONE);
									tx_btnopen.setVisibility(View.VISIBLE);
									String qrStr = LLingOpenDoorHandler
											.getSingle(getActivity()).createDoorControlQR(PrefUtils.getStrPrefData(getActivity(), "linglingID", ""), keys, 10, 3, 0, "123456AA");//llingId, keys, validTime, validCount, authLevel(梯控参数，门禁则默认0), encryptKey
									try {
										
										Bitmap bitmap = CodeCreator.createQRCode(qrStr);
										img_erweima.setImageBitmap(bitmap);
									} catch (WriterException e) {
										e.printStackTrace();
									}
									img_message.setBackgroundResource(R.drawable.cat4);
									tx_message.setText("告诉你一个秘密手机摇一摇也可以开门哦！本二维码可在10分钟使用3次，您再次进入系统会重新生成！");
									img_erweima.setBackgroundResource(0);
								}

							}


						}else if("1".equals(jsonObject.getString("ref"))){
							PrefUtils.removeStrPrefData(getActivity(), "linglingID");//删除本地数据令令ID
							PrefUtils.removeStrPrefData(getActivity(), "keys");//删除本地数据秘钥
							PrefUtils.removeStrPrefData(getActivity(), "user_phone");//删除本地数据
							tx_btnactivity.setVisibility(View.VISIBLE);
							tx_btnopen.setVisibility(View.GONE);
							img_message.setBackgroundResource(R.drawable.cat4);
							tx_message.setText("您的开门权限已过期，请联系物业！");
							img_erweima.setBackgroundResource(0);
							img_erweima.setBackgroundResource(R.drawable.defaulterweima);
						}else{
							Toast.makeText(getActivity(), jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}


			});
		}else{
			Toast.makeText(getActivity(), "糟糕,网络异常!", Toast.LENGTH_LONG).show();
		}

	}
	 private SensorEventListener sensorEventListener = new SensorEventListener() {
	        @Override
	        public void onSensorChanged(SensorEvent event) {
	            long currentUpdateTime = System.currentTimeMillis();
	            long timeInterval = currentUpdateTime - lastUpdateTime;
	            if (timeInterval < UPTATE_INTERVAL_TIME) {
	                return;
	            }
	            lastUpdateTime = currentUpdateTime;
	// 传感器信息改变时执行该方法
	            float[] values = event.values;
	            float x = values[0]; // x轴方向的重力加速度，向右为正
	            float y = values[1]; // y轴方向的重力加速度，向前为正
	            float z = values[2]; // z轴方向的重力加速度，向上为正
	            float deltaX = x - lastX;
	            float deltaY = y - lastY;
	            float deltaZ = z - lastZ;


	            lastX = x;
	            lastY = y;
	            lastZ = z;
	            double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY
	                    + deltaZ * deltaZ) / timeInterval) * 100;
	            if (speed >= SPEED_SHRESHOLD) {
	                vibrator.vibrate(300);
	                String[] key = (String[])keys.toArray(new String[0]);
					LLingOpenDoorConfig config = new LLingOpenDoorConfig(9, key);
					LLingOpenDoorHandler handler = LLingOpenDoorHandler.getSingle(getActivity());
					handler.doOpenDoor(config, listener);
	                
	            }
	        }


	        @Override
	        public void onAccuracyChanged(Sensor sensor, int accuracy) {

	        }
	    };

}
